import { t } from 'i18next'
import { subscribeWithSelector } from 'zustand/middleware'
import create from 'zustand'
import Alert from '@/components/Alert'
import { useMccStore } from '../../store'
import {
	DragDataNativeMonitor,
	IMessage,
	ISocketServerConfig,
	IWebToNativeDefaultConfig,
	StartMonitorCometd,
	StopMonitorCometd,
	typeEventMap,
} from './interface'
import {
	getBrowserLeftBottomPosition,
	compareVersion,
	hasBigVersion,
	isLinuxSys,
	getDomScreenPosition,
} from '../../utils/utils'
import ReconnectingWebSocket from 'reconnecting-websocket'
import {
	MONITOR_EXE_HAS_INSTALLED,
	MONITOR_SOCKET_PORT,
	NO_REMIND_EXE_INSTALLED,
	NO_REMIND_UPDATE_VERSION,
} from './constant'
import { useTableAllStore } from '../main/table/all/store'
import { getItemByMtKey } from '../main/table/all/utils'
import { fetchGetMTChnInfo } from '@/api/manager/tvwall'
import { useCameraRcStore } from '../cameraRc/store'
import { Environment, getUrlParams } from '@/utils'
import { useGlobalStore } from '@/store/global'
import { IMcc } from '@/api/manager/type'
import { useRollCallStore } from '../roll/store'
import { MtEntity } from '@/api/manager/mt'

type StateStore = {
	linuxVersion: string
	exeVersion: string
	localIP: string
	ssoCookieKey: string
	monitorApiAddress: string
	/** 是否准备完成，含连接成功，并注册成功. exe本身开机自启 */
	hasReady: boolean
	isFirstWebLoad: boolean
	/** 会场监控权限 */
	hasMonitor: 0 | 1
	NeedMustUpdateExeVersion: boolean
	minSupportVersion: string
	WsInstance: ReconnectingWebSocket | null
	socketServerConfig: ISocketServerConfig
	WebToNativeDefaultConfig: IWebToNativeDefaultConfig
	_isUpdateDialog: boolean
	_isLinuxDialogOpen: boolean
	_isWinDialogOpen: boolean
}
type IStore = StateStore & {
	reset: () => void
	init: () => void
	update: (d: Partial<StateStore>) => void
	updateSocketServerConfig: (d: Partial<ISocketServerConfig>) => void
	updateWebToNativeDefaultConfig: (d: Partial<IWebToNativeDefaultConfig>) => void
	appCheckHasReadyAndStart: () => boolean
	webSocketStart: (config?: { tryCount: number }) => void
	webToNativeEntry: (funcKey: string, param?: any) => void
	webToNativeEntryOnMessage: (data: IMessage) => void
	dealHasReady: () => void
	/** 显示安装框 */
	showSetUpDialog: () => void
	/** 显示更新框 */
	showUpdateDialog: (isFirst?: boolean) => void
	showNativeVideo: (mtid: string, type: 1 | 2 | 3) => void
	/** 开启远遥 */
	showCamera: () => void
	/** 关闭远遥 */
	closeCamera: () => void
	showRollCallDialog: (mt?: MtEntity, nextMt?: MtEntity) => void
	showRollCall: (val?: number) => void
	closeRollCall: () => void
	clearRollCall: () => void
	startMonitor: (data: StartMonitorCometd) => void
	stopMonitor: (data: StopMonitorCometd) => void
	getDefaultParams: (type: keyof IWebToNativeDefaultConfig) => any
	nativeMonitorDropParse: (mt: IMcc) => DragDataNativeMonitor | {}
}
const monitorSocketPort = localStorage.getItem(MONITOR_SOCKET_PORT)
/** 是否安装 */
export const getMonitorExeHasInstalled = () => localStorage.getItem(MONITOR_EXE_HAS_INSTALLED) || ''
/** 是否不要提示安装, 存储的是版本号 */
export const getNoRemindMonitorExeInstalled = () => localStorage.getItem(NO_REMIND_EXE_INSTALLED) || ''
/** 是否不要提示升级, 存储的是版本号 */
export const getNoRemindUpdateVersion = () => localStorage.getItem(NO_REMIND_UPDATE_VERSION) || ''

const initialState: StateStore = {
	linuxVersion: '',
	exeVersion: '',
	localIP: '',
	ssoCookieKey: '',
	monitorApiAddress: '',
	minSupportVersion: '',
	hasReady: false,
	isFirstWebLoad: true,
	hasMonitor: 0,
	NeedMustUpdateExeVersion: false,
	WsInstance: null,
	socketServerConfig: {
		protocol: window.location.protocol,
		url: 'localhost', //TS.Helper.Utils.getUrlValueByKey('local_ip') || localIP || '127.0.0.1', // 10.82.0.15 本地exe的Socket连接IP
		port: monitorSocketPort != null ? monitorSocketPort : isLinuxSys() ? '5010' : '1010', //本地exe端口
		conf_id: '', //这里获取不到，下面settimeout
		conf_name: '',
		mt_id: '',
		client_id: 0, //客户端标webSocket注册后才有的
		support_dragdrop: 1,
	},
	WebToNativeDefaultConfig: {
		//默认下参格式
		KCMP_REGISTER_REQ: {
			event: 'KCMP_REGISTER_REQ',
			server_ip: '',
			local_ip: '',
			conf_id: '',
			conf_name: '',
			mt_id: '',
			sso_cookie_key: '',
			support_monitor: 1, //是否支持监控终端与画面合成
			video_format: {
				type: 0,
				h264: 0,
				frame: 25,
				bitrate: 1024,
				resolution: 3,
			},
			browser: '', //如是IE,则传ie
			server_site: window.location.protocol + '//' + window.location.host, //带个http/https
		},
		KCMP_START_MONITOR_CMD: {
			event: 'KCMP_START_MONITOR_CMD',
			conf_id: '', //即会议E164
			mt_id: '', //合并mt_id和mcuidx
			alias: '',
			v_snd_chn: [],
			a_snd_chn: [],
		},
		KCMP_UPDATE_STREAM_PARAM_CMD: {
			event: 'KCMP_UPDATE_STREAM_PARAM_CMD',
			mode: 0, //0-视频1-音频
			src: {
				encrypt: {
					mode: 0,
					key: '123456',
				},
				payload_formats: {
					real_payload: '96',
					active_payload: '106',
				},
				media_formats: {
					sampling: 0, // 音频采样率，仅音频时需
					chn_num: 0, // 声道数，仅音频时需
					bitrate: 8128,
					max_frame: 30, // 帧率，仅视频时需
				},
				rtcp: {
					ip: '127.0.0.1',
					port: 6655,
				},
			},
			dst: {
				ip: '12.12.12.12',
				port: 6615,
			},
		},
		KCMP_STOP_PLAY_CMD: {
			event: 'KCMP_STOP_PLAY_CMD',
			dst: [
				{
					ip: '12.12.12.12',
					port: 6615,
				},
			],
		},
		KCMP_SHOW_MONITOR_WINDOW_CMD: {
			event: 'KCMP_SHOW_MONITOR_WINDOW_CMD',
			default_expand: true,
			screen_x: 100,
			screen_y: 200,
			ScreenX: 100,
			ScreenY: 200,
		},
		KCMP_SHOW_REVIEW_WINDOW_CMD: {
			client_id: 0,
			event: 'KCMP_SHOW_REVIEW_WINDOW_CMD',
			init_position: [15, 20], // 初始位置x, y
			extend_x: 1, // 0-向右展开 1-向左展开
			extend_y: 0, // 0-向下展开 1-向上展开
		},
		KCMP_CLOSE_REVIEW_WINDOW_CMD: {
			event: 'KCMP_CLOSE_REVIEW_WINDOW_CMD',
			client_id: 0,
		},
		KCMP_CHANGE_REVIEW_CMD: {
			event: 'KCMP_CHANGE_REVIEW_CMD',
			conf_id: '1122334',
			mt_id: '12.12.12.4',
			alias: t('测试终端'),
			client_id: 111, //客户端id
			v_snd_chn: [
				//终端音视频流信息
				{
					chn_id: 1,
					chn_alias: 'xxxx',
				},
				{
					chn_id: 2,
					chn_alias: 'xxxx',
				},
			],
			a_snd_chn: [],
		},
		KCMP_SHOW_ROLL_CALL_WINDOW_CMD: {
			client_id: 0,
			event: 'KCMP_SHOW_ROLL_CALL_WINDOW_CMD',
			init_position: [15, 20], // 初始位置x, y
			extend_x: 1, // 0-向右展开 1-向左展开
			extend_y: 0, // 0-向下展开 1-向上展开
			callpoll_num: 1, //被点名人
		},
		KCMP_CLOSE_ROLL_CALL_WINDOW_CMD: {
			event: 'KCMP_CLOSE_ROLL_CALL_WINDOW_CMD',
			client_id: 0,
		},
		KCMP_CLEAR_CALLEE_CMD: {
			event: 'KCMP_CLEAR_CALLEE_CMD',
			client_id: 0,
		},
		KCMP_UPDATE_CONF_NAME_NTF: {
			event: 'KCMP_UPDATE_CONF_NAME_NTF',
			conf_id: '1122334', //即会议E164
			conf_name: 'new name', //新的会议名称
		},
	},
	_isUpdateDialog: false,
	_isLinuxDialogOpen: false,
	_isWinDialogOpen: false,
}

//监控的分辨率是mcu的分辨率，而不是会管api的分辨率，需要转化下
function transResolution(r: 1 | 2 | 3 | 12 | 13 | 14 | 15 | 16) {
	switch (r) {
		case 1:
			return 3 //已经没有 1 了，这边给默认值
		case 2:
			return 3
		case 3:
			return 5
		case 12:
			return 32
		case 13:
			return 35
		case 14:
			return 15
		case 15:
			return 31
		case 16:
			return 62
		default:
			return 3
	}
}

export const useMonitorStore = create<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		updateSocketServerConfig: (d) => {
			const { socketServerConfig } = get()
			let _data = { ...socketServerConfig, ...d }
			set({ socketServerConfig: _data })
		},
		updateWebToNativeDefaultConfig: (d) => {
			const { WebToNativeDefaultConfig } = get()
			let _data = { ...WebToNativeDefaultConfig, ...d }
			set({ WebToNativeDefaultConfig: _data })
		},
		reset: () => set(initialState),
		init: () => {
			const {
				monitorApiAddress,
				linuxVersion,
				exeVersion,
				localIP,
				WebToNativeDefaultConfig,
				hasReady,
				WsInstance,
				updateWebToNativeDefaultConfig,
				webSocketStart,
				update,
			} = get()
			update({ minSupportVersion: isLinuxSys() ? linuxVersion : exeVersion })
			updateWebToNativeDefaultConfig({
				KCMP_REGISTER_REQ: {
					...WebToNativeDefaultConfig.KCMP_REGISTER_REQ,
					server_ip: monitorApiAddress,
					local_ip: getUrlParams('local_ip') || localIP || '127.0.0.1',
				},
			})
			const meetingType = useMccStore.getState().mccInfo.meetingType
			if (!('WebSocket' in window) || meetingType === 2) {
				return
			}
			// let _onbeforeunload = window.onbeforeunload || function () {}
			window.onbeforeunload = function (ev) {
				//unloadNeedClose 注：exe暂不支持 先加上
				if (hasReady && WsInstance) {
					//主动调一下
					WsInstance.close()
				}
				// _onbeforeunload(ev)
			}
			webSocketStart()
		},
		appCheckHasReadyAndStart: () => {
			const { hasReady, WsInstance, webSocketStart } = get()
			console.log('AppCheckHasReadyAndStart')
			if (!hasReady) {
				if (!('WebSocket' in window)) {
					Alert(t('当前浏览器不支持此功能，推荐使用Chrome及IE11浏览器'))
				} else {
					if (!(WsInstance != null && WsInstance.readyState === ReconnectingWebSocket.OPEN)) {
						//拉起exe
						let isBlur = false
						let timer: NodeJS.Timeout | null = null
						const onBlur = () => {
							isBlur = true
						}
						// 0.1秒内发生了blur，则等待focus发生触发回调
						const onFocus = () => {
							if (isBlur) {
								timer && clearTimeout(timer)
								webSocketStart({ tryCount: 2 })
							}
							isBlur = false
							window.removeEventListener('blur', onBlur)
							window.removeEventListener('focus', onFocus)
						}
						window.addEventListener('blur', onBlur)
						window.addEventListener('focus', onFocus)
						// 触发打开应用
						let iframe = document.createElement('iframe')
						iframe.src = 'kcmp:'
						iframe.style.display = 'none'
						document.body.appendChild(iframe)
						setTimeout(function () {
							document.body.removeChild(iframe)
						}, 100)
						// 0.1秒内没有发生blur（没有询问）则回未安装或已记住都会触
						timer = setTimeout(function () {
							window.addEventListener('blur', onBlur)
							if (!isBlur) {
								window.removeEventListener('focus', onFocus)
								webSocketStart({ tryCount: 2 })
							}
						}, 100)
					}
				}
			}
			return hasReady
		},
		webSocketStart: (config) => {
			const {
				hasMonitor,
				ssoCookieKey,
				socketServerConfig,
				update,
				dealHasReady,
				webToNativeEntry,
				webToNativeEntryOnMessage,
				updateSocketServerConfig,
				getDefaultParams,
			} = get()
			let option = {
				tryCount: 1,
				...(config || {}),
			}
			let connString = 'wss://' + socketServerConfig.url + ':' + socketServerConfig.port
			console.log(connString, '======connString=========')
			let ws = null
			try {
				ws = new ReconnectingWebSocket(connString, [], {
					debug: false,
					reconnectionDelayGrowFactor: 0,
					connectionTimeout: 3000,
					maxRetries: option.tryCount, //最多连接次数
				})
			} catch (e) {
				console.log(e, '=======ReconnectingWebSocket=====')
				return
			}
			//连接websocket
			ws.addEventListener('open', function () {
				console.log('=========onopen==========')
				//连接成功后立马注册一致
				setTimeout(function () {
					const {
						e164,
						meetingMoid,
						subject,
						mediaFormat,
						mediaH264,
						meetingRate,
						meetingResolution,
						frame,
					} = useMccStore.getState().mccInfo
					updateSocketServerConfig({ conf_id: e164, conf_name: subject, mt_id: meetingMoid })
					let param = getDefaultParams('KCMP_REGISTER_REQ')
					param.conf_id = e164
					param.conf_name = subject
					param.mt_id = meetingMoid
					param.support_monitor = hasMonitor
					param.sso_cookie_key = ssoCookieKey
					param.video_format = {
						type: mediaFormat === 4 ? 106 : 108,
						h264: mediaH264,
						frame: frame,
						bitrate: meetingRate,
						resolution: transResolution(meetingResolution),
					}
					if (Environment.isIE) {
						param.browser = 'ie'
					}
					//注册
					webToNativeEntry('Register', param)
				}, 200)
			})
			//接收消息
			ws.addEventListener('message', function (evt) {
				var innerCodeObj = JSON.parse(evt.data)
				console.log(innerCodeObj, '=========onmessage============')
				//接收消息统一处理
				webToNativeEntryOnMessage(innerCodeObj)
			})
			//关闭连接
			ws.addEventListener('close', function () {
				update({ hasReady: false })
				console.log('WebSocketClosed!')
			})
			let leftTryCount = option.tryCount,
				entryTryCount = option.tryCount
			ws.addEventListener('error', function () {
				leftTryCount = leftTryCount - 1
				//首次页面加载时的尝试
				if (leftTryCount === 0 && entryTryCount === 1) {
					update({ isFirstWebLoad: true })
					dealHasReady()
					return
				}
				if (leftTryCount === 0 && entryTryCount > 1) {
					update({ isFirstWebLoad: false })
					dealHasReady()
					return
				}
			})
			update({ WsInstance: ws })
		},
		webToNativeEntry: (funcKey, param) => {
			//不允许加任务业务逻辑,为最终发送入口，并且只能从Entry
			const { WsInstance, getDefaultParams } = get()
			if ('WebSocket' in window && WsInstance && WsInstance.readyState === ReconnectingWebSocket.OPEN) {
				console.log(param, t('WebToNative.Entry入参Key:') + funcKey)
				//如果有client_id参数，但没传则不发
				if (
					param != undefined &&
					param['client_id'] != undefined &&
					(param.client_id.length === 0 || param.client_id == 0)
				) {
					console.log('需要client_id但无：' + JSON.stringify(param))
					return
				}
				switch (funcKey) {
					case 'Register':
						param = param || getDefaultParams('KCMP_REGISTER_REQ')
						WsInstance.send(JSON.stringify(param))
						break
					case 'ShowMonitor':
						const isExpand =
							useGlobalStore.getState().user?.personal_config.monitor_type === 2 ? true : false
						let _KCMP_SHOW_MONITOR_WINDOW_CMD = getDefaultParams('KCMP_SHOW_MONITOR_WINDOW_CMD')
						_KCMP_SHOW_MONITOR_WINDOW_CMD.default_expand = isExpand
						//浏览器窗口定位
						var browserLeftBottomPos = getBrowserLeftBottomPosition()
						// console.log(browserLeftBottomPos, t('===========浏览器窗口定位============'))
						_KCMP_SHOW_MONITOR_WINDOW_CMD.screen_x = browserLeftBottomPos.x + 1
						_KCMP_SHOW_MONITOR_WINDOW_CMD.screen_y = browserLeftBottomPos.y - 155
						if (Environment.isIE && window.screen.availHeight <= window.outerHeight) {
							_KCMP_SHOW_MONITOR_WINDOW_CMD.screen_y = browserLeftBottomPos.y - 171
						}
						param = _KCMP_SHOW_MONITOR_WINDOW_CMD
						break
					case 'SetMonitorAudioAndVideoBasicInfo':
						param = param || getDefaultParams('KCMP_START_MONITOR_CMD')
						break
					case 'StartMonitor': //显示画面
						param = param || getDefaultParams('KCMP_UPDATE_STREAM_PARAM_CMD')
						break
					case 'StopMonitor': //停止显示画面
						param = param || getDefaultParams('KCMP_STOP_PLAY_CMD')
						break
					case 'CloseMonitor': //关闭监控框
						param = param || getDefaultParams('KCMP_STOP_PLAY_CMD')
						break
					case 'ShowCamera': //显示摄像头
						param = param || getDefaultParams('KCMP_SHOW_REVIEW_WINDOW_CMD')
						break
					case 'ChangeCamera': //变更摄像头
						param = param || getDefaultParams('KCMP_CHANGE_REVIEW_CMD')
						break
					case 'CloseCamera': //关闭摄像头
						param = param || getDefaultParams('KCMP_CLOSE_REVIEW_WINDOW_CMD')
						break
					case 'ShowRollCall': //显示轮询
						param = param || getDefaultParams('KCMP_SHOW_ROLL_CALL_WINDOW_CMD')
						break
					case 'ChangeRollCallCurrent': //与远摇共格式
						param = param || getDefaultParams('KCMP_CHANGE_REVIEW_CMD')
						break
					case 'ChangeRollCallNext': //与远摇共格式
						param = param || getDefaultParams('KCMP_CHANGE_REVIEW_CMD')
						break
					case 'CloseRollCall':
						param = param || getDefaultParams('KCMP_CLOSE_ROLL_CALL_WINDOW_CMD')
						break
					case 'ClearRollCall':
						param = param || getDefaultParams('KCMP_CLEAR_CALLEE_CMD')
						break
					case 'UpdateMeetingName':
						param = param || getDefaultParams('KCMP_UPDATE_CONF_NAME_NTF')
						break
				}
				WsInstance.send(JSON.stringify(param))
			}
		},
		webToNativeEntryOnMessage: (data) => {
			const {
				hasMonitor,
				minSupportVersion,
				socketServerConfig,
				update,
				updateSocketServerConfig,
				webToNativeEntry,
				showUpdateDialog,
				getDefaultParams,
			} = get()
			switch (data.event) {
				case 'KCMP_REGISTER_ACK': //接收注册回复通知
					update({ hasReady: true })
					updateSocketServerConfig({ client_id: data.client_id, support_dragdrop: data['support_dragdrop'] })
					localStorage.setItem(MONITOR_EXE_HAS_INSTALLED, new Date().toLocaleDateString())
					console.log(data.version, '======注册所得版本号=======')
					console.log(minSupportVersion, '======后台txt版本号=====')
					console.log(minSupportVersion, '======最小兼容版本=======')
					let isNeedUpdate = compareVersion(minSupportVersion, data.version)
					console.log(isNeedUpdate, '=======IsDiffVersion=======')
					update({ NeedMustUpdateExeVersion: isNeedUpdate })
					if (isNeedUpdate) {
						showUpdateDialog(true)
					}
					if (isNeedUpdate && hasBigVersion(minSupportVersion, data.version)) {
						update({ NeedMustUpdateExeVersion: true })
						return
					}
					//如果未能是ie白名单,刚提示. 并且监控不显示
					if (socketServerConfig.support_dragdrop === 0) {
						Alert(t('会议监控需要操作本地文件!请将此网站设为信任站点,然后再重新打开浏览器'))
					} else {
						//默认打开窗口
						setTimeout(function () {
							if (hasMonitor) {
								webToNativeEntry('ShowMonitor')
							}
						}, 100)
					}
					break
				case 'KCMP_DRAG_DROP':
					let tree = useTableAllStore.getState().tree
					let item = getItemByMtKey(tree, data.mt_id)?.mcc as any
					let mt = item
						? {
								mtid: item.mtid || item.mtKey, //会议没有mtid
								name: item.name,
								mtKey: item.mtKey,
								accountType: item.accountType,
								id: item.id, //只会议有id
						  }
						: {
								mtid: '',
								name: '',
								mtKey: '',
								accountType: 1,
								id: 0,
						  }
					// console.log(mt, t('============回调找到的mt============='))
					const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
					let mt_id = mt.mtid
					if (mt.id === '0_1') {
						//上级会议
						let mtids = mt.mtid.split(/[\._]/)
						mt_id = mtids[mtids.length - 1]
					}
					fetchGetMTChnInfo(meetingMoid, mt_id).then((res) => {
						if (res.success) {
							let arr = res.list ?? []
							let param = getDefaultParams('KCMP_START_MONITOR_CMD')
							param.conf_id = useMccStore.getState().mccInfo.e164
							param.mt_id = mt.mtid.split('_').join('.')
							param.alias = mt.name || ''
							param.window_id = data.window_id
							param.client_id = socketServerConfig.client_id
							param.v_snd_chn = arr.map((item) => ({
								chn_id: item.v_snd_chn_id,
								chn_alias: '',
							}))
							param.a_snd_chn = arr.map((item) => ({
								chn_id: item.a_snd_chn_id,
								chn_alias: '',
							}))
							webToNativeEntry('SetMonitorAudioAndVideoBasicInfo', param)
						} else {
							Alert(t('获取终端信息失败'))
						}
					})
					break
				case 'KCMP_REVIEW_WINDOW_CLOSE_NTF':
					// console.log(t('web收到exe的通知KCMP_REVIEW_WINDOW_CLOSE_NTF'))
					useCameraRcStore.setState({ isToggleIconActive: false })
					break
				case 'KCMP_ROLL_CALL_WINDOW_CLOSE_NTF':
					// console.log(t('web收到exe的通知KCMP_ROLL_CALL_WINDOW_CLOSE_NTF'))
					//关闭眼睛
					useRollCallStore.setState({ openShow: false })
					break
				default:
					break
			}
		},
		dealHasReady: () => {
			const { hasReady, isFirstWebLoad, showSetUpDialog } = get()
			if (!('WebSocket' in window)) {
				return
			}
			let monitorExeHasInstalled = getMonitorExeHasInstalled()
			let noRemindMonitorExeInstalled = getNoRemindMonitorExeInstalled()
			console.log(monitorExeHasInstalled, '=========monitorExeHasInstalled===========')
			console.log(noRemindMonitorExeInstalled, '=========noRemindMonitorExeInstalled===========')
			console.log(isFirstWebLoad, '=========isFirstWebLoad=========')
			if (isFirstWebLoad) {
				//首次页面加载
				//显示前提 1.socket没连接 2.没安装  3.未勾选不再提示含版本
				if (!hasReady && !monitorExeHasInstalled && !noRemindMonitorExeInstalled) {
					showSetUpDialog()
				}
			} else {
				if (!hasReady) {
					showSetUpDialog()
				}
			}
		},
		showSetUpDialog: () => {
			const { hasMonitor, update } = get()
			if (!hasMonitor) return
			if (isLinuxSys()) {
				update({ _isLinuxDialogOpen: true, _isUpdateDialog: false })
			} else {
				update({ _isWinDialogOpen: true, _isUpdateDialog: false })
			}
		},
		showUpdateDialog: (isFirst) => {
			const { hasMonitor, isFirstWebLoad, minSupportVersion, update } = get()
			if (!hasMonitor) return
			update({ isFirstWebLoad: isFirst ?? false })
			const isStorageDiffVersion = compareVersion(minSupportVersion, getNoRemindUpdateVersion())
			if (!isStorageDiffVersion && isFirstWebLoad) {
				return
			}
			if (isLinuxSys()) {
				update({ _isLinuxDialogOpen: true, _isUpdateDialog: true })
			} else {
				update({ _isWinDialogOpen: true, _isUpdateDialog: true })
			}
		},
		showNativeVideo: function (mtid, type) {
			const { webToNativeEntry, showCamera, showRollCall, socketServerConfig } = get()
			let tree = useTableAllStore.getState().tree
			let item = getItemByMtKey(tree, mtid)?.mcc as any
			if (!mtid) {
				console.log('显示终端为空')
				return
			}
			let mt = item
				? {
						mtid: item.mtid || item.mtKey,
						name: item.name,
						mtKey: item.mtKey,
						accountType: item.accountType,
						id: item.id,
				  }
				: {
						mtid: '',
						name: '',
						mtKey: '',
						accountType: 1,
						id: 0,
				  }
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			let mt_id = mt.mtid
			if (mt.id === '0_1') {
				//上级会议
				let mtids = mt.mtid.split(/[\._]/)
				mt_id = mtids[mtids.length - 1]
			}
			fetchGetMTChnInfo(meetingMoid, mt_id).then((res) => {
				if (res.success) {
					let arr = res.list ?? []
					let param = {
						event: typeEventMap[type] || 'KCMP_CHANGE_REVIEW_CMD',
						conf_id: useMccStore.getState().mccInfo.e164,
						mt_id: mt.mtid.split('_').join('.'),
						alias: mt.name || '',
						client_id: socketServerConfig.client_id,
						v_snd_chn: arr.map((item) => ({
							chn_id: item.v_snd_chn_id,
							chn_alias: '',
						})),
						a_snd_chn: arr.map((item) => ({
							chn_id: item.a_snd_chn_id,
							chn_alias: '',
						})),
					}
					//多流的话 远摇/点名只给中屏
					if (arr.length === 3) {
						param.v_snd_chn = [
							{
								chn_id: arr[1].v_snd_chn_id,
								chn_alias: '',
							},
						]
						param.a_snd_chn = [
							{
								chn_id: arr[1].a_snd_chn_id,
								chn_alias: '',
							},
						]
					}
					if (type === 1) {
						//打开监控
						showCamera()
						//开始监
						webToNativeEntry('ChangeCamera', param)
					} else if (type === 2) {
						//打开点名
						showRollCall()
						//开始点
						webToNativeEntry('ChangeRollCallCurrent', param)
					} else if (type === 3) {
						//打开点名
						showRollCall()
						//开始点
						webToNativeEntry('ChangeRollCallNext', param)
					}
				} else {
					Alert(t('获取终端信息失败'))
				}
			})
		},
		showCamera: () => {
			const { socketServerConfig, webToNativeEntry, getDefaultParams } = get()
			let param = getDefaultParams('KCMP_SHOW_REVIEW_WINDOW_CMD')
			param.client_id = socketServerConfig.client_id
			let splitDom = document.querySelector('#mcc-split')
			if (splitDom) {
				let screenPosition = getDomScreenPosition(splitDom)
				param.init_position = [screenPosition.x - 4, screenPosition.y]
				if (!Environment.isIE && window.screen.availHeight <= window.outerHeight) {
					param.init_position = [screenPosition.x - 4, screenPosition.y + 8]
				}
			}
			webToNativeEntry('ShowCamera', param)
			useCameraRcStore.setState({ isToggleIconActive: true })
		},
		closeCamera: () => {
			const { socketServerConfig, webToNativeEntry, getDefaultParams } = get()
			let param = getDefaultParams('KCMP_CLOSE_REVIEW_WINDOW_CMD')
			param.client_id = socketServerConfig.client_id
			webToNativeEntry('CloseCamera', param)
			//图标需要去除active
			useCameraRcStore.setState({ isToggleIconActive: false })
		},
		showRollCallDialog: (mt, nextMt) => {
			const {
				NeedMustUpdateExeVersion,
				closeRollCall,
				showSetUpDialog,
				clearRollCall,
				showRollCall,
				showNativeVideo,
				closeCamera,
			} = get()
			closeCamera()
			if (NeedMustUpdateExeVersion) {
				showSetUpDialog()
				return
			}
			//显示前都清清掉画面
			clearRollCall()
			if (useGlobalStore.getState().user?.personal_config.roll_call_type === 2) {
				//显示当前被点名人和下一个被点名人
				showRollCall(2)
				if (mt) {
					showNativeVideo(mt.mt_id, 2)
				}
				if (nextMt) {
					showNativeVideo(nextMt.mt_id, 3)
				}
			} else {
				//仅显示点名人
				showRollCall(1)
				if (mt) {
					showNativeVideo(mt.mt_id, 2)
				}
			}
		},
		showRollCall: (number) => {
			const { socketServerConfig, getDefaultParams, webToNativeEntry } = get()
			let param = getDefaultParams('KCMP_SHOW_ROLL_CALL_WINDOW_CMD')
			param.client_id = socketServerConfig.client_id
			param.callpoll_num = number || 1
			let splitDom = document.querySelector('#mcc-split')
			if (splitDom) {
				let screenPosition = getDomScreenPosition(splitDom)
				param.init_position = [screenPosition.x - 4, screenPosition.y]
				if (!Environment.isIE && window.screen.availHeight <= window.outerHeight) {
					param.init_position = [screenPosition.x - 4, screenPosition.y + 8]
				}
			}
			webToNativeEntry('ShowRollCall', param)
		},
		closeRollCall: () => {
			const { socketServerConfig, getDefaultParams, webToNativeEntry } = get()
			//关闭眼睛
			useRollCallStore.setState({ openShow: false })
			let param = getDefaultParams('KCMP_CLOSE_ROLL_CALL_WINDOW_CMD')
			param.client_id = socketServerConfig.client_id
			webToNativeEntry('CloseRollCall', param)
		},
		clearRollCall: () => {
			const { socketServerConfig, getDefaultParams, webToNativeEntry } = get()
			let param = getDefaultParams('KCMP_CLEAR_CALLEE_CMD')
			param.client_id = socketServerConfig.client_id
			webToNativeEntry('ClearRollCall', param)
		},
		startMonitor: (data) => {
			const { getDefaultParams, webToNativeEntry } = get()
			let param = getDefaultParams('KCMP_UPDATE_STREAM_PARAM_CMD')
			param.mode = parseInt(data.media_mode) === 2 ? 1 : 0 // 监控exe下参 0-视频 1-音频
			param.src.encrypt.mode = parseInt(data.encrypt_param.encrypt_mode)
			param.src.encrypt.key = data.encrypt_param.encrypt_key
			param.src.payload_formats.real_payload = data.double_payload.real_payload
			param.src.payload_formats.active_payload = data.double_payload.active_payload
			param.src.media_formats.sampling = parseInt(data.audio_sample_freq)
			param.src.media_formats.chn_num = parseInt(data.audio_chnl_num)
			param.src.media_formats.bitrate = parseInt(data.aaccap.bitrate)
			param.src.media_formats.max_frame = parseInt(data.aaccap.max_frame_num)
			param.src.rtcp.ip = data.srcrtcp_addr.ip
			param.src.rtcp.port = parseInt(data.srcrtcp_addr.port)
			param.dst.ip = data.dst_addr.ip
			param.dst.port = parseInt(data.dst_addr.port)
			webToNativeEntry('StartMonitor', param)
		},
		stopMonitor: (data) => {
			const { getDefaultParams, webToNativeEntry } = get()
			let param = getDefaultParams('KCMP_STOP_PLAY_CMD')
			if (data.dst_addr && data.dst_addr.length > 0) {
				param.dst = data.dst_addr.map((item) => ({
					ip: item.ip,
					port: parseInt(item.port),
				}))
			}
			webToNativeEntry('StopMonitor', param)
		},
		getDefaultParams: (type) => {
			const { WebToNativeDefaultConfig } = get()
			return JSON.parse(JSON.stringify(WebToNativeDefaultConfig[type]))
		},
		nativeMonitorDropParse: (mt) => {
			const { socketServerConfig } = get()
			if (mt.isMt && mt.status.isOnline) {
				return {
					client_id: socketServerConfig.client_id,
					conf_id: socketServerConfig.conf_id,
					mt_id: mt.mtKey,
				}
			} else {
				return {}
			}
		},
	}))
)
